import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs';
import { environment } from '../../../environments/environment';

export interface TestCase {
  input: string;
  expectedOutput: string;
  isSample: boolean;
}

export interface ProblemCreateRequest {
  title: string;
  description: string;
  difficulty: string;
  timeLimit: number;
  memoryLimit: number;
  testCases: TestCase[];
}

export interface ProblemUpdateRequest extends ProblemCreateRequest {
  id?: number;
}

export interface ProblemDTO {
  id: number;
  title: string;
  description: string;
  difficulty: string;
  timeLimit: number;
  memoryLimit: number;
  testCases: TestCase[];
  authorId: number;
  createdAt: string;
  updatedAt: string;
}

export interface AdminResponse<T> {
  success: boolean;
  message: string;
  data?: T;
}

@Injectable({
  providedIn: 'root'
})
export class AdminService {
  private apiUrl = `${environment.apiUrl}/admin`;

  constructor(private http: HttpClient) { }

  private getHeaders(): HttpHeaders {
    const token = localStorage.getItem('token');
    return new HttpHeaders({
      'Authorization': `Bearer ${token}`,
      'Content-Type': 'application/json'
    });
  }

  /**
   * 创建新题目
   */
  createProblem(problem: ProblemCreateRequest): Observable<AdminResponse<ProblemDTO>> {
    return this.http.post<AdminResponse<ProblemDTO>>(
      `${this.apiUrl}/problems`,
      problem,
      { headers: this.getHeaders() }
    );
  }

  /**
   * 更新题目
   */
  updateProblem(id: number, problem: ProblemUpdateRequest): Observable<AdminResponse<ProblemDTO>> {
    return this.http.put<AdminResponse<ProblemDTO>>(
      `${this.apiUrl}/problems/${id}`,
      problem,
      { headers: this.getHeaders() }
    );
  }

  /**
   * 删除题目
   */
  deleteProblem(id: number): Observable<AdminResponse<void>> {
    return this.http.delete<AdminResponse<void>>(
      `${this.apiUrl}/problems/${id}`,
      { headers: this.getHeaders() }
    );
  }

  /**
   * 获取所有题目（管理员视图）
   */
  getAllProblems(): Observable<AdminResponse<ProblemDTO[]>> {
    return this.http.get<AdminResponse<ProblemDTO[]>>(
      `${this.apiUrl}/problems`,
      { headers: this.getHeaders() }
    );
  }

  /**
   * 获取题目详情（管理员视图）
   */
  getProblem(id: number): Observable<AdminResponse<ProblemDTO>> {
    return this.http.get<AdminResponse<ProblemDTO>>(
      `${this.apiUrl}/problems/${id}`,
      { headers: this.getHeaders() }
    );
  }

  /**
   * 批量创建题目
   */
  batchCreateProblems(problems: ProblemCreateRequest[]): Observable<AdminResponse<ProblemDTO[]>> {
    return this.http.post<AdminResponse<ProblemDTO[]>>(
      `${this.apiUrl}/problems/batch`,
      problems,
      { headers: this.getHeaders() }
    );
  }
} 